import React, { useEffect, useState } from 'react';
import Taro from '@tarojs/taro';
import { connect } from 'react-redux';
import { Button, Text, Textarea, View } from '@tarojs/components';
import CommentImagePicker from '@/components/Comment/ImagePicker';
import CommentRate from '@/components/Comment/Rate';
import utils from '@/utils/index';
import {
  commentUploadImgServer,
  confirmProductCommentServer,
  getCommentScoreTypeServer,
} from '@/services/comment';
import Imagelocation from '@/components/Imagelocation';
import { sourceUrl } from '@/config';

const toast = (title, callback) => {
  callback = callback || (() => {});
  Taro.showToast({ title, icon: 'none', duration: 1000 });
  setTimeout(() => {
    callback();
  }, 1000);
};

const Product = ({ order = {}, dispatch }) => {
  //提交评价的数据
  const [state, updateState] = useState({
    orderId: '',
    productList: [],
    org: {
      topicId: 0,
      scoreList: [],
    },
  });

  const [uploadMap, setUploadMap] = useState({});

  const [productScoreType, setProductScoreType] = useState(null);

  const setState = (val) => {
    const res = { ...state, ...val };
    updateState(res);
  };

  //初始化
  const init = async () => {
    state.orderId = order.id;
    state.merchantId = order.merchantId;
    state.orgId = order.storeId;
    state.org.topicId = order.storeId;
    state.productList = order.items.map((item) => {
      const product = {
        title: item.title,
        topicId: item.productId,
        imgUrls: '',
        content: '',
        scoreTypeId: 0,
        score: 0,
        mediaUrl: item.mediaUrl,
        topicBizTitle: item.title,
      };

      if (item.optionValue) {
        product['extra'] = {
          productImg:
            item.mediaUrl?.indexOf('http') === 0 ? item.mediaUrl : sourceUrl + item.mediaUrl,
          specification: JSON.parse(item.optionValue),
          specificationId: item.variantId,
        };
      }
      return product;
    });
    //商品评分类型
    const productScoreTypeRes = await getCommentScoreTypeServer({ appId: 'thjs_shop_product' });
    if (productScoreTypeRes.code === '1' && productScoreTypeRes.content.length) {
      setProductScoreType(productScoreTypeRes.content[0]);
      state.productList = state.productList.map((item) => ({
        ...item,
        scoreTypeId: productScoreTypeRes.content[0].scoreTypeId,
      }));
    }
    //商城评分类型
    const orgScoreTypeRes = await getCommentScoreTypeServer({ appId: 'thjs_shop_org' });
    if (orgScoreTypeRes.code === '1') {
      state.org.scoreList = orgScoreTypeRes.content.map((item) => ({ ...item, score: 0 }));
    }
    setState(state);
  };

  useEffect(() => {
    order.id && init();
  }, [order]);

  //选择图片
  const handleImagePicker = (files, product) => {
    product.imgUrls = files.join(',');
    setState(state);
  };

  //评分
  const handleRate = (val, item) => {
    item.score = val;
    setState(state);
  };

  //评价内容
  const handleInput = (val, product) => {
    product.content = val.detail.value;
    setState(state);
  };

  //刷新订单列表
  const refreshOrderList = () => {
    dispatch({
      type: 'order/setRefreshOrderId',
      payload: order.id,
    });
  };

  //提交评价
  const confirm = async () => {
    let params = JSON.parse(JSON.stringify(state));
    if (
      params.productList.filter((item) => item.score == 0).length ||
      params.org.scoreList.filter((item) => item.score == 0).length
    ) {
      toast('您还没有为星级打分');
      return;
    }
    Taro.showLoading({ title: '提交中~', mask: true });
    let files = {};
    for (let product of params.productList) {
      let tmp = {};
      const imgUrls = product.imgUrls ? product.imgUrls.split(',') : [];
      for (let file of imgUrls) {
        console.log('file:', file);
        if (!!uploadMap[file]) {
          //避免重复上传
          tmp[file] = uploadMap[file];
          continue;
        }
        const fileRes = await commentUploadImgServer(file);
        console.log('fileRes:', fileRes);
        if (fileRes.code == 1 && fileRes.content) {
          tmp[file] = fileRes.content;
        }
      }
      Object.assign(files, tmp);
      product.imgUrls = Object.values(tmp).join(',');
    }

    setUploadMap({
      ...uploadMap,
      ...files,
    });

    if (params.extra) {
      params.extra = JSON.stringify(params.extra);
    }

    confirmProductCommentServer(params).then((res) => {
      Taro.hideLoading();
      if (res.code == 1) {
        toast('提交成功', () => {
          utils.backWithRefreash();
          refreshOrderList();
        });
      } else {
        toast(res.message);
      }
    });
  };

  return (
    <View className="submitCommentPage">
      <View className="submitCommentContent">
        {state.productList.map((product, idx) => (
          <View className="part1" key={idx}>
            <View className="partContent">
              {/*商品信息*/}
              <View className="productInfo">
                <Imagelocation
                  className="pic"
                  src={
                    product.mediaUrl.indexOf('http') === 0
                      ? product.mediaUrl
                      : sourceUrl + product.mediaUrl
                  }
                  type="product"
                />
                <View className="text">
                  <View>{product.title}</View>
                  {!!product.extra && (
                    <View className="tagList">
                      {Object.keys(product.extra.specification).map((item, index) => (
                        <Text className="tag" key={index}>
                          {item}:{product.extra.specification[item]}
                        </Text>
                      ))}
                    </View>
                  )}
                </View>
              </View>
              {/*评价打分*/}
              {!!productScoreType && (
                <View className="shopRate">
                  <CommentRate
                    showText
                    value={product.score}
                    onChange={(val) => handleRate(val, product)}
                  >
                    {productScoreType.name}
                  </CommentRate>
                </View>
              )}
              {/*评价内容*/}
              <Textarea
                className="textarea"
                onInput={(val) => handleInput(val, product)}
                placeholder="从多个角度评价宝贝，可以帮助更多想买的人"
                maxlength={120}
              />
              {/*买家图片*/}
              <CommentImagePicker onChange={(files) => handleImagePicker(files, product)} />
            </View>
          </View>
        ))}
        <View className="part2">
          <View className="partContent">
            <View className="shopTitle">{order.storeName}</View>
            {/*评价打分*/}
            {state.org.scoreList.map((item) => (
              <View className="shopRate" key={item.scoreTypeId}>
                <CommentRate showText value={item.score} onChange={(val) => handleRate(val, item)}>
                  {item.name}
                </CommentRate>
              </View>
            ))}
          </View>
        </View>
        <View className="part3 flexMiddle">
          <Button className="btn customePageBackgroundStyle flexMiddle" onClick={confirm}>
            提交评价
          </Button>
        </View>
      </View>
    </View>
  );
};

export default connect(() => ({}))(Product);
